package com.bykj.taketurns.activity;

import android.app.ActivityManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bilibili.magicasakura.utils.ThemeUtils;
import com.bykj.taketurns.R;
import com.bykj.taketurns.utils.Constant;
import com.bykj.taketurns.utils.ObjectUtil;
import com.bykj.taketurns.utils.TextUtil;
import com.bykj.taketurns.utils.ToastUtils;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by carolina on 2017/6/28.
 * activity基类
 */

public abstract class BaseActivity extends FragmentActivity implements View.OnClickListener {
    /***
     * 保存的Activity状态
     */
    private Bundle savedInstanceState;
    //当前是否被开启
    private boolean hasStarted;
    private static final int REQUEST_CODE_PERMISSON = 2020; //权限请求码

    private boolean isNeedCheckPermission = true; //判断是否需要检测，防止无限弹框申请权限
    private TextView tv_title_allmy;
    private ImageView iv_back_allmy;
    private TextView tv_right_allmy;
    //数据解析用的
    public Gson gson = new Gson();

    //用来在做网络请求的时候封装的数据
    public Map<String,String> map;
    // 退出时间

    private long currentBackPressedTime = 0;

    // 退出间隔

    private static final int BACK_PRESSED_INTERVAL = 2000;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getParentView() > 0)
            setContentView(getParentView());
        this.savedInstanceState = savedInstanceState;
        hasStarted = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        map = new HashMap<>();
        //初始化ToolBar
        initToolBar();

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    /**
     * 初始化控件
     */
    public abstract void initView(Bundle savedInstanceState);

    /**
     * 加载数据
     */
    public abstract void initData(Bundle savedInstanceState);


    /**
     * 找控件
     */
    public View setViewById(int resId) {
        View view = findViewById(resId);
        return view;
    }

    /**
     * 获得当前所加载的视图
     */
    public abstract int getParentView();

    /**
     * 开启
     */
    @Override
    protected void onStart() {
        super.onStart();
        if (hasStarted) {
            initView(savedInstanceState);
            initData(savedInstanceState);
            hasStarted = false;
        }
    }

    //初始化ToolBar
    public abstract void initToolBar();

    public void inittHeaderWidget() {
        tv_title_allmy = findViewById(R.id.tv_title_allmy);
        iv_back_allmy = findViewById(R.id.iv_back_allmy);
        tv_right_allmy = findViewById(R.id.tv_right_allmy);

    }

    public void setTitle(String title) {//设置中间文字的内容

        tv_title_allmy.setText(title);
    }

    public void BtnLeftListener(View.OnClickListener listener) {//右边文字隐藏

        iv_back_allmy.setOnClickListener(listener);
        tv_right_allmy.setVisibility(View.GONE);
    }

    public void BtnListener(View.OnClickListener listener) {//右边文字显示

        iv_back_allmy.setOnClickListener(listener);
        tv_right_allmy.setOnClickListener(listener);
        tv_right_allmy.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(ThemeUtils.getColorById(this, R.color.theme_color_primary_dark));
            ActivityManager.TaskDescription description = new ActivityManager.TaskDescription(null, null,
                    ThemeUtils.getThemeAttrColor(this, android.R.attr.colorPrimary));
            setTaskDescription(description);
        }
    }

    /**
     * 是否要Activity销毁时取消注册EventBus
     *
     * @return 返回true表示要取消，否则不取消，默认为不取消
     */
    public boolean unregisterEventBusOnDestroy() {
        return false;
    }

    /**
     * 接收到EventBus发布的消息事件
     *
     * @param event 消息事件
     */
    @CallSuper
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveMessage(@NonNull MessageEvent event) {
        Log.d("onReceiveMessage...", "" + (event == null ? "null" : event));
    }

    /***
     * 创建传输字段的MessageEvent
     */
    public static class MessageEvent { /* Additional fields if needed */
    }

    /**
     * 显示Toast提示信息
     *
     * @param message 消息文本
     */
    public final void showToast(@NonNull String message) {
        ToastUtils.showShortMessage(message);
    }

    /**
     * 显示Toast提示信息
     *
     * @param resId string.xml中的字符串资源ID
     */
    public final void showToast(@StringRes int resId) {
        ToastUtils.showShortMessage(resId);
    }


    @CallSuper
    @Override
    public void onResume() {
        //获取焦点.
        if (isNeedCheckPermission) {
            checkAllNeedPermissions();
        }
        // 竖屏显示
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        super.onResume();
        postData();
    }
    protected abstract void postData();

    @CallSuper
    @Override
    protected void onPause() {
        super.onPause();
        //暂停

    }

    @CallSuper
    @Override
    protected void onRestart() {
        super.onRestart();

    }

    @CallSuper
    @Override
    public void onLowMemory() {
        super.onLowMemory();

    }

    @CallSuper
    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    /**
     * 隐藏软件盘
     */
    public void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 点击软键盘之外的空白处，隐藏软件盘
     *
     * @param ev
     * @return
     */
//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//            View v = getCurrentFocus();
//            if (ToolUtil.isShouldHideInput(v, ev)) {
//
//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                if (imm != null) {
//                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
//                }
//            }
//            return super.dispatchTouchEvent(ev);
//        }
//        // 必不可少，否则所有的组件都不会有TouchEvent了
//        if (getWindow().superDispatchTouchEvent(ev)) {
//            return true;
//        }
//        return super.dispatchTouchEvent(ev);
//    }

    /**
     * 显示软键盘
     */
    public void showInputMethod() {
        if (getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.showSoftInputFromInputMethod(getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 防止快速点击
     *
     * @return
     */
    private boolean fastClick() {
        long lastClick = 0;
        if (System.currentTimeMillis() - lastClick <= 1000) {
            return false;
        }
        lastClick = System.currentTimeMillis();
        return true;
    }

    /**
     * 跳转到指定的Activity
     *
     * @param targetActivity 要跳转的目标Activity
     */
    protected final void startActivity(@NonNull Class<?> targetActivity) {
        startActivity(new Intent(this, targetActivity));
    }

    /**
     * 跳转到指定的Activity
     *
     * @param flags          intent flags
     * @param targetActivity 要跳转的目标Activity
     */
    protected final void startActivity(int flags, @NonNull Class<?> targetActivity) {
        final Intent intent = new Intent(this, targetActivity);
        intent.setFlags(flags);
        startActivity(new Intent(this, targetActivity));
    }

    /**
     * 跳转到指定的Activity
     *
     * @param data           Activity之间传递数据，Intent的Extra key为Constant.EXTRA_NAME.DATA
     * @param targetActivity 要跳转的目标Activity
     */
    protected final void startActivity(@NonNull Bundle data, @NonNull Class<?> targetActivity) {
        final Intent intent = new Intent();
        intent.putExtra(Constant.EXTRA_NAME, data);
        intent.setClass(this, targetActivity);
        startActivity(intent);
    }

    /**
     * 跳转到指定的Activity
     *
     * @param extraName      要传递的值的键名称
     * @param extraValue     要传递的String类型值
     * @param targetActivity 要跳转的目标Activity
     */
    public final void startActivity(@NonNull String extraName, @NonNull String extraValue, @NonNull Class<?> targetActivity) {
        if (TextUtil.isEmptyAndNull(extraName))
            throw new NullPointerException("传递的值的键名称为null或空");
        final Intent intent = new Intent(getApplicationContext(), targetActivity);
        intent.putExtra(extraName, extraValue);
        startActivity(intent);
    }

    /**
     * 获取通过Intent对象传递过来的参数
     *
     * @param name 参数名称
     * @return 从intent和bundle中都没有取到返回null，否则返回传递过来的参数值
     */
    public final String getStringExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.notNull(intent)) {
            // 如果intent不为空，则先从intent中取，如果没有再从bundle中取，如果都没有就返回null
            final String extra = intent.getStringExtra(name);
            if (ObjectUtil.isNull(extra)) {
                final Bundle data = intent.getExtras();
                if (ObjectUtil.notNull(data)) {
                    return data.getString(name);
                }
            } else
                return extra;
        }
        return null;
    }

    /**
     * 获取通过Intent对象传递过来的参数
     *
     * @param name         Extra参数名称
     * @param defaultValue 没有在intent或bundle对象中找到时设置的默认值
     * @return 从intent和bundle中都没有取到返回设置的默认值，否则返回传递过来的参数值
     */
    public final String getStringExtra(@NonNull String name, String defaultValue) {
        final String extra = getStringExtra(name);
        if (ObjectUtil.isNull(extra))
            return defaultValue;
        return extra;
    }

    /**
     * 获取通过Intent对象传递过来的参数
     *
     * @param name 参数名称
     * @return 从intent和bundle中都没有取到返回null，否则返回传递过来的参数值
     */
    public final boolean getBooleanExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.notNull(intent)) {
            // 如果intent不为空，则先从intent中取，如果没有再从bundle中取，如果都没有就返回false
            final boolean extra = intent.getBooleanExtra(name, false);
            if (!extra) {
                final Bundle data = intent.getExtras();
                if (ObjectUtil.notNull(data)) {
                    return data.getBoolean(name);
                }
            }
            return extra;
        }
        return false;
    }

    /**
     * 获取通过Intent对象传递过来的参数
     *
     * @param name         Extra参数名称
     * @param defaultValue 没有在intent或bundle对象中找到时设置的默认值
     * @return 从intent和bundle中都没有取到返回设置的默认值，否则返回传递过来的参数值
     */
    public final boolean getBooleanExtra(@NonNull String name, boolean defaultValue) {
        final boolean extra = getBooleanExtra(name);
        if (extra)
            return defaultValue;
        return extra;
    }

    /**
     * 获取通过Intent对象传递过来的参数
     *
     * @param name 参数名称
     * @return 从intent和bundle中都没有取到返回null，否则返回传递过来的参数值
     */
    public final int getIntExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.notNull(intent)) {
            // 如果intent不为空，则先从intent中取，如果没有再从bundle中取，如果都没有就返回-1
            final int extra = intent.getIntExtra(name, -1);
            if (extra == -1) {
                final Bundle data = intent.getExtras();
                if (ObjectUtil.notNull(data)) {
                    return data.getInt(name);
                }
            }
            return extra;
        }
        return -1;
    }

    /**
     * 获取通过Intent对象传递过来的参数
     *
     * @param name         Extra参数名称
     * @param defaultValue 没有在intent或bundle对象中找到时设置的默认值
     * @return 从intent和bundle中都没有取到返回设置的默认值，否则返回传递过来的参数值
     */
    public final int getIntExtra(@NonNull String name, int defaultValue) {
        final int extra = getIntExtra(name);
        if (extra == -1)
            return defaultValue;
        return extra;
    }

    public final short getShortExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.isNull(intent))
            return 0;
        return intent.getShortExtra(name, Short.valueOf("0"));
    }

    public final int getShortExtra(@NonNull String name, short defaultValue) {
        final Intent intent = getIntent();
        if (ObjectUtil.isNull(intent))
            return 0;
        return intent.getShortExtra(name, defaultValue);
    }

    public final long getLongExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.isNull(intent))
            return 0L;
        return intent.getLongExtra(name, 0L);
    }

    public final long getLongExtra(@NonNull String name, long defaultValue) {
        final Intent intent = getIntent();
        if (ObjectUtil.isNull(intent))
            return 0L;
        return intent.getLongExtra(name, defaultValue);
    }

    /**
     * 获取通过Intent对象传递过来的参数
     *
     * @param name 参数名称
     * @return 从intent和bundle中都没有取到返回0.0f，否则返回传递过来的参数值
     */
    public final float getFloatExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.notNull(intent)) {
            // 如果intent不为空，则先从intent中取，如果没有再从bundle中取，如果都没有就返回0.0f
            final float extra = intent.getFloatExtra(name, 0.0f);
            if (extra == 0.0f) {
                final Bundle data = intent.getExtras();
                if (ObjectUtil.notNull(data)) {
                    return data.getFloat(name);
                }
            }
            return extra;
        }
        return 0.0f;
    }

    /**
     * 获取通过Intent对象传递过来的参数
     *
     * @param name         Extra参数名称
     * @param defaultValue 没有在intent或bundle对象中找到时设置的默认值
     * @return 从intent和bundle中都没有取到返回设置的默认值，否则返回传递过来的参数值
     */
    public final float getFloatExtra(@NonNull String name, float defaultValue) {
        final float extra = getFloatExtra(name);
        if (extra == 0.0f)
            return defaultValue;
        return extra;
    }

    /**
     * 获取通过Intent对象传递过来的参数
     *
     * @param name 参数名称
     * @return 从intent和bundle中都没有取到返回0.0，否则返回传递过来的参数值
     */
    public final double getDoubleExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.notNull(intent)) {
            // 如果intent不为空，则先从intent中取，如果没有再从bundle中取，如果都没有就返回0.0
            final double extra = intent.getDoubleExtra(name, 0.0);
            if (extra == 0.0) {
                final Bundle data = intent.getExtras();
                if (ObjectUtil.notNull(data)) {
                    return data.getDouble(name);
                }
            }
            return extra;
        }
        return 0.0;
    }

    /**
     * 获取通过Intent对象传递过来的参数
     *
     * @param name         Extra参数名称
     * @param defaultValue 没有在intent或bundle对象中找到时设置的默认值
     * @return 从intent和bundle中都没有取到返回0.0，否则返回传递过来的参数值
     */
    public final double getDoubleExtra(@NonNull String name, double defaultValue) {
        final double extra = getDoubleExtra(name);
        if (extra == 0.0)
            return defaultValue;
        return extra;
    }

    public final Parcelable getParcelableExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.isNull(intent))
            return null;
        return intent.getParcelableExtra(name);
    }

    public final Parcelable[] getParcelableArrayExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.isNull(intent))
            return null;
        return intent.getParcelableArrayExtra(name);
    }

    public final ArrayList<Parcelable> getParcelableArrayListExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.isNull(intent))
            return null;
        return intent.getParcelableArrayListExtra(name);
    }

    public final Serializable getSerializableExtra(@NonNull String name) {
        final Intent intent = getIntent();
        if (ObjectUtil.isNull(intent))
            return null;
        return intent.getSerializableExtra(name);
    }

    /**
     * 检查所有权限，无权限则开始申请相关权限
     */
    protected void checkAllNeedPermissions() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return;
        List<String> needRequestPermissonList = getDeniedPermissions(getNeedPermissions());
        if (null != needRequestPermissonList && needRequestPermissonList.size() > 0) {
            ActivityCompat.requestPermissions(this, needRequestPermissonList.toArray(
                    new String[needRequestPermissonList.size()]), REQUEST_CODE_PERMISSON);
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                needRequestPermissonList.add(permission);
            }
        }
        return needRequestPermissonList;
    }

    /**
     * 所有权限是否都已授权
     *
     * @return
     */
    protected boolean isGrantedAllPermission() {
        List<String> needRequestPermissonList = getDeniedPermissions(getNeedPermissions());
        return needRequestPermissonList.size() == 0;
    }

    /**
     * 权限授权结果回调
     *
     * @param requestCode
     * @param permissions
     * @param paramArrayOfInt
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] paramArrayOfInt) {
        if (requestCode == REQUEST_CODE_PERMISSON) {
            if (!verifyPermissions(paramArrayOfInt)) {
                permissionGrantedFail();
                showTipsDialog();
                isNeedCheckPermission = false;
            } else permissionGrantedSuccess();
        }
    }

    /**
     * 检测所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示提示对话框
     */
    protected void showTipsDialog() {
        new AlertDialog.Builder(this).setTitle("提示信息").setMessage("当前应用缺少" + getDialogTipsPart()
                + "权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                }).show();
    }


    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /**
     * 获取弹框提示部分内容
     *
     * @return
     */
    protected String getDialogTipsPart() {
        return "必要";
    }

    /**
     * 获取需要进行检测的权限数组
     */
    protected  String[] getNeedPermissions(){
        return new String[0];
    }

    /**
     * 权限授权成功
     */
    protected  void permissionGrantedSuccess(){

    }

    /**
     * 权限授权失败
     */
    protected  void permissionGrantedFail(){

    }

    protected void setStatusBar() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary));
    }


    //重写onBackPressed()方法,继承自退出的方法

    @Override

    public void onBackPressed() {
        if(this instanceof HomeActivity){
            // 判断时间间隔

            if (System.currentTimeMillis()- currentBackPressedTime > BACK_PRESSED_INTERVAL) {

                currentBackPressedTime = System.currentTimeMillis();

                Toast.makeText(this, "再按一次返回键退出程序", Toast.LENGTH_SHORT).show();

            }else {
                finish();
            }

        }else{
            finish();
        }




    }
}
